package cn.harry.cabinet.dao

import androidx.lifecycle.LiveData
import androidx.room.*
import cn.harry.cabinet.model.entity.HardwareDevice

/**
 * 硬件设备配置DAO
 */
@Dao
interface HardwareDeviceDao {
    
    /**
     * 插入设备配置
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insert(device: HardwareDevice): Long
    
    /**
     * 批量插入设备配置
     */
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAll(devices: List<HardwareDevice>)
    
    /**
     * 更新设备配置
     */
    @Update
    suspend fun update(device: HardwareDevice)
    
    /**
     * 删除设备配置
     */
    @Delete
    suspend fun delete(device: HardwareDevice)
    
    /**
     * 获取所有设备配置
     */
    @Query("SELECT * FROM hardware_devices ORDER BY deviceType")
    fun getAllDevices(): LiveData<List<HardwareDevice>>
    
    /**
     * 获取所有设备配置（非LiveData）
     */
    @Query("SELECT * FROM hardware_devices ORDER BY deviceType")
    suspend fun getAllDevicesList(): List<HardwareDevice>
    
    /**
     * 根据设备类型获取设备配置
     */
    @Query("SELECT * FROM hardware_devices WHERE deviceType = :deviceType")
    suspend fun getDeviceByType(deviceType: String): HardwareDevice?
    
    /**
     * 根据设备类型获取设备配置（LiveData）
     */
    @Query("SELECT * FROM hardware_devices WHERE deviceType = :deviceType")
    fun getDeviceByTypeLive(deviceType: String): LiveData<HardwareDevice?>
    
    
    /**
     * 获取所有启用的设备配置
     */
    @Query("SELECT * FROM hardware_devices WHERE enabled = 1 ORDER BY deviceType")
    fun getEnabledDevices(): LiveData<List<HardwareDevice>>
    
    /**
     * 获取所有启用的设备配置（非LiveData）
     */
    @Query("SELECT * FROM hardware_devices WHERE enabled = 1 ORDER BY deviceType")
    suspend fun getEnabledDevicesList(): List<HardwareDevice>
    
    /**
     * 更新设备启用状态
     */
    @Query("UPDATE hardware_devices SET enabled = :enabled, updateTime = :updateTime WHERE deviceType = :deviceType")
    suspend fun updateDeviceEnabled(deviceType: String, enabled: Boolean, updateTime: Long = System.currentTimeMillis())
    
    /**
     * 更新设备串口配置
     */
    @Query("""
        UPDATE hardware_devices 
        SET serialPort = :serialPort, 
            baudRate = :baudRate, 
            dataBits = :dataBits, 
            stopBits = :stopBits, 
            parity = :parity,
            updateTime = :updateTime 
        WHERE deviceType = :deviceType
    """)
    suspend fun updateDeviceSerialConfig(
        deviceType: String,
        serialPort: String,
        baudRate: Int,
        dataBits: Int,
        stopBits: Int,
        parity: Int,
        updateTime: Long = System.currentTimeMillis()
    )
    
    /**
     * 清空所有设备配置
     */
    @Query("DELETE FROM hardware_devices")
    suspend fun deleteAll()
    
    /**
     * 获取设备数量
     */
    @Query("SELECT COUNT(*) FROM hardware_devices")
    suspend fun getDeviceCount(): Int
}
